package edu.whut.mall.admin.service.impl;


import edu.whut.mall.admin.service.ISysRoleResourceService;
import edu.whut.mall.mapper.SysRoleResourcesMapper;
import edu.whut.mall.model.SysRoleResources;
import edu.whut.mall.model.SysRoleResourcesExample;
import edu.whut.mall.model.SysUserRoleExample;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: footbook
 * @description:
 * @author: Wayne
 * @create: 2020-03-18 09:27
 **/
@Service
@RequiredArgsConstructor
public class SysRoleResourceServiceImpl implements ISysRoleResourceService {

    private final SysRoleResourcesMapper sysRoleResourceMapper;

    @Override
    public Integer assignResource2Role(Long roleId, String resourceIdString) {
        clearResourcesToRole(roleId);
        if(StringUtils.isNotBlank(resourceIdString)) {
            String[] resourceString = resourceIdString.split(",");
            long[] resourceIds= Arrays.stream(resourceString).mapToLong(Long::parseLong).distinct().toArray();
            List<SysRoleResources> sysRoleResourcesList=new ArrayList<>(resourceIds.length);
            Arrays.stream(resourceIds).forEach(id->{
                SysRoleResources sysRoleResources=new SysRoleResources();
                sysRoleResources.setRoleId(roleId);
                sysRoleResources.setResourcesId(id);
                sysRoleResourcesList.add(sysRoleResources);
            });
            return sysRoleResourceMapper.batchInsert(sysRoleResourcesList);
        }
        else{
            return -1;
        }
    }


    private void clearResourcesToRole(Long roleId){
        SysRoleResourcesExample example = new SysRoleResourcesExample();
        example.createCriteria().andRoleIdEqualTo(roleId);
        sysRoleResourceMapper.deleteByExample(example);
    }
}
